/*
 * Copyright (C) 2004-2006 nickyb@users.sourceforge.net
 * 
 * This file is part of FreeQueryBuilder (http://querybuilder.sourceforge.net)
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package net.sourceforge.querybuilder;

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class QuerySyntax extends JScrollPane
{
	QueryModel querymodel;
	
	private QueryBuilder builder;
	private JTextArea text;
	
	private boolean distinct;
	
	QuerySyntax(QueryBuilder builder)
	{
		this.builder = builder;
		
		setViewportView(text = new JTextArea());
		text.setEditable(false);
		text.setOpaque(false);
		text.setTabSize(4);
		
		builder.getActionMap().put("select-distinct",new ActionDistinct());
		builder.getActionMap().put("copy-syntax"	,new ActionCopySyntax());
	}

	void clear()
	{
		querymodel = null;
	}
	
	public boolean isDistinct()
	{
		return distinct;
	}
	
	public void setDistinct(boolean b)
	{
		distinct = b;
		refresh();
	}
	
	public void setText(String s)
	{
		text.setText(s);
	}
	
	public String getText()
	{
		return text.getText();
	}
	
	void refresh()
	{
		if(builder.diagram.getEntityCount() == 0)
		{
			builder.syntax.setText(null);
			return;
		}
		
		querymodel = QueryModel.save(builder);
		builder.syntax.setText(querymodel.getSyntax());
	}		
	
	private class ActionDistinct extends AbstractAction
	{
		ActionDistinct()
		{
			this.putValue(NAME, "distinct");
			this.putValue(SHORT_DESCRIPTION, "distinct");
		}
		
		public void actionPerformed(ActionEvent e)
		{
			QuerySyntax.this.setDistinct(!QuerySyntax.this.isDistinct());
		}
	}
	
	private class ActionCopySyntax extends AbstractAction
	{
		ActionCopySyntax()
		{
			putValue(NAME,"copy syntax");
			putValue(SHORT_DESCRIPTION, "copy syntax");
		}
		
		public void actionPerformed(ActionEvent e)
		{
			QuerySyntax.this.text.selectAll();
			QuerySyntax.this.text.copy();
		}
	}
}
